<?php


namespace app\common\model;


use think\Db;

class PaperQuestions extends Base
{
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ddt_exam_paperques';
    // 主键ID
    protected $pk = 'pq_id';

    /**
     * @param array $where  // 查询的条件
     * @param string $item  // 查询的参数
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function getOne($where=[1], $item='*',$orderby = "")
    {
        $rs = $this
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->find();

        return $rs;
    }

    function api_get_list($cond, $orderby="pq.sort desc", $item="*")
    {
        $where = null;

        if(!empty($cond['paper_id'])){
            $where[] = ['pq.paper_id', '=', $cond['paper_id']];
        }
        if(!empty($cond['ques_ids'])){
            $where[] = ['pq.ques_id','in',implode(',',$cond['ques_ids'])];
        }

        $rs = $this
            ->alias('pq')
            ->leftJoin('ddt_exam_ques q','pq.ques_id = q.ques_id')
            ->field($item)
            ->where($where)
            ->order($orderby)
            ->select()
            ->each(function($item){
//                去除反序列化后的空数组
                $options = array_filter(unserialize($item['option']));
                array_walk($options,function(&$v,$k){// 注意&$v
                    $new['the_option'] = $k;
                    $new['the_text'] = $v;
//                    var_dump($k);
                    $v = $new;
                });
                $item['option'] = array_values($options);
                return $item;
            });
        return $rs;
    }

    //新增、编辑(后台操作)
    function edit($params, $id=0){
        if($id>0){
            // 更新条件
            $where = ["{$this->pk}" => $id];
            $rs = $this->allowField(true)->save($params, $where);
        }else{
            if(!isset($params['add_time'])){
                $params['add_time'] = time();
            }
            // 更新数据
            $this->allowField(true)->save($params);
            $rs = $this->pk;
        }
        if ($rs === false) {
            $this->setError(-1, '操作失败');
            return false;
        }
        return $rs;
    }

}